import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState, useRef, forwardRef, useImperativeHandle, useEffect, } from "react";
import DropDownButton from "devextreme-react/drop-down-button";
import { Checkbox, Popover, Input, Button, message, Radio } from "antd";
import CpasIcon from "~/public/cpas-ui/components-ui/components/Icon";
import CpasModalComponent from "../Validator";
import CpasMergeModal from "../RowMerge";
import CpasSort from "../Sort";
import CpasFilter from "../Filter";
import CpasTailDiff from "../TailDifference";
import _ from "lodash";
import { getDsToZlData } from "../../api/DesignTableApi";
import { MergeType, getHbTypeByZcbfid } from "../../../../tools/Tools";
const directionOptions = [
    {
        value: "vertical",
        label: "纵向",
        key: 1,
    },
    {
        value: "horizontal",
        label: "横向",
        key: 2,
    },
];
export const resetSessionDismantleData = () => {
    console.log("-----------清除sessionStorage数据 ----------------");
    sessionStorage.removeItem("cpasData");
    sessionStorage.removeItem("rule");
    sessionStorage.removeItem("allHeaderColumn");
    sessionStorage.removeItem("hideColumnArr");
    sessionStorage.removeItem("hideColumnKeyArr");
    sessionStorage.removeItem("dismantleTableMode");
    sessionStorage.removeItem("importDismantledTableJson");
    sessionStorage.removeItem("importedReverseInfo");
    sessionStorage.removeItem("reverseInfo");
    sessionStorage.removeItem("souceData");
    sessionStorage.removeItem("preventStyleLoss");
};
window.onbeforeunload = function () {
    //清除sessionStorage值
    resetSessionDismantleData();
};
let cpassRef;
let dismantleTableMode = false;
const ReductionEditor = forwardRef((props, ref) => {
    const { _this, className } = props;
    console.log("hshshs ", _this?.gridRef?.tableConfig?.filterCfg?.num, _this?.gridRef?.tableConfig);
    const [isHiddenMergeRow, setIsHiddenMergeRow] = useState(_this?.gridRef?.tableConfig?.filterCfg?.num ? true : false);
    // 勾稽校验设置弹框
    const [isOpen, setIsOpenModal] = useState(false);
    const [isMergeOpen, setIsMergeOpenModal] = useState(false);
    const [isFilterOpen, setIsFilterOpenModal] = useState(false);
    const [isSortOpen, setIsSortOpenModal] = useState(false);
    const [isTailDifference, setIsTailDifference] = useState(false);
    const [isDirectionOpen, setIsDirectionOpenModal] = useState(false);
    const [hiddenPopoverVisible, setHiddenPopoverVisible] = useState(false);
    const dismantRule = useRef(null);
    const [dismantleTableWindowOpen, setDismantleTableWindowOpen] = useState(false); // 控制拆表窗口显示隐藏
    const [directionVal, setDirectionVal] = useState("vertical");
    const handleOpenChange = (newOpen) => {
        setDismantleTableWindowOpen(newOpen);
    };
    const onShowModal = () => {
        setIsOpenModal(!isOpen);
    };
    const onShowMergeModal = () => {
        setIsMergeOpenModal(!isMergeOpen);
    };
    const onShowFilterModal = () => {
        setIsFilterOpenModal(!isFilterOpen);
    };
    const onShowSortModal = () => {
        setIsSortOpenModal(!isSortOpen);
    };
    const onShowTailDifference = () => {
        setIsTailDifference(!isTailDifference);
    };
    const onShowDirectionModal = () => {
        setIsDirectionOpenModal(!isDirectionOpen);
    };
    const handleHiddenPopoverVisibleChange = (visible) => {
        setHiddenPopoverVisible(visible);
    };
    const handleDirectionPopoverVisibleChange = (visible) => {
        setIsDirectionOpenModal(visible);
    };
    useImperativeHandle(ref, () => ({
        setDismantleTableWindowOpen: setDismantleTableWindowOpen,
        setIsHiddenMergeRow: setIsHiddenMergeRow,
        directionVal,
    }));
    // //声明整理模式下移动行的函数
    // //批量移动时遵循一个原则，当队头触顶或者队伍触底则整体不移动
    // const handleMoveRow = (direction) => {
    //   const ranges: CellRange[] = _this.gridRef.state.currentRange;
    //   if (!ranges) {
    //     _this.showErrorNotify("请选择行进行操作");
    //     return;
    //   }
    //   const movesRow = []; //需要移动的行
    //   const afterMoveRange = []; //需要划选的单元格范围
    //   for (let i = 0; i < ranges.length; i++) {
    //     const range = ranges[i];
    //     const { computedMovesRows, computedAfterMoveRange } =
    //       _this.gridRef.gridService.getMoveRows(range, direction);
    //     //如果有计算结果则进行移动数组填充
    //     if (computedMovesRows.length > 0 && computedAfterMoveRange.length > 0) {
    //       movesRow.push(...computedMovesRows);
    //       afterMoveRange.push(computedAfterMoveRange);
    //     }
    //   }
    //   //调用移动行服务
    //   _this.gridService.moveRowsByDirection(movesRow);
    //   if (afterMoveRange.length > 0) {
    //     //调用移动后的划选
    //     _this.hot.selectCells(afterMoveRange);
    //   }
    // };
    //
    // //声明整理模式下移动列的函数
    // const handleMoveColumn = (direction) => {
    //   //TODO 必须选择表头才能进行移动
    //
    //   //获取要移动的列
    //   const { computedMovesColumns, matchSelectTopHeader } =
    //     _this.headerService.getMoveColumns(direction);
    //   if (computedMovesColumns.length > 0) {
    //     //调用移动列服务
    //     const { gridData, computedAfterMoveRange } =
    //       _this.headerService.moveColumnsByComputedMovesColumns(
    //         computedMovesColumns
    //       );
    //     //刷新表格
    //     // _this.hot.render();
    //     // TODO 利用重载的方式可以避免列样式重叠的问题. 但是会重刷当前表格状态。无法保留之前的交互状态. 例如：选中的单元格。 而且会妨碍会影响回撤功能。但是回撤功能目前还没有实现。实现机制可以根据刷表的方式回撤
    //     _this.gridRef.reloadTable(gridData);
    //
    //     const topLevelHeaderKeys = matchSelectTopHeader.map((item) => {
    //       return item.key;
    //     });
    //
    //     _this.headerService.selectNodeByKey(topLevelHeaderKeys);
    //   }
    // };
    const yinCangPopoverContent = (_this) => {
        // if (sessionStorage.dismantleTableMode) {
        //   dismantleTableMode = JSON.parse(sessionStorage.dismantleTableMode);
        // }
        dismantleTableMode = _this.gridRef.tableConfig.dismantleTableMode;
        // 去查 headerColumn 动态取列名
        const columnArr = _this.headerService.getVisibleColumn();
        let hideColumnKeyArr;
        // hideColumnKeyArr = sessionStorage.hideColumnKeyArr
        //   ? JSON.parse(sessionStorage.hideColumnKeyArr)
        //   : [];
        hideColumnKeyArr = _this.gridRef.tableConfig.hideColumnKeyArr;
        return (_jsx("div", { children: columnArr?.map((item, index) => (_jsx("p", { children: _jsx(Checkbox, { disabled: false, onChange: (event) => _this.onProjectChange(item, event), defaultChecked: hideColumnKeyArr?.includes(item.key), children: item.label }, item.key) }))) }));
    };
    const onDirectionChange = async (e) => {
        const value = e.target.value;
        console.log(_this, "_this1111");
        const dsSourceData = _this.gridRef.dsSourceData;
        const tableConfig = _this.gridRef.tableConfig;
        const dsFormulaSourceData = _this.gridRef.props.dsTableRef.getFormulaSourceData();
        const newTableCfg = {
            ...tableConfig,
            directionCfg: {
                direction: value,
            },
        };
        try {
            console.log(newTableCfg, "newTableCfg", value);
            const tid = _this?.gridRef?.props?.notes?.tid;
            const zlTableData = await getDsToZlData(dsSourceData, newTableCfg, dsFormulaSourceData, tid);
            if (zlTableData && zlTableData.data) {
                console.log("进入条件111");
                const zlTransformData = zlTableData.data;
                //zlGridData 除了拆表的转数逻辑 , 数据库会存储该数据
                //zlDivideData 拆表后的转数逻辑
                //zlGridData 存储在隐藏的CpasTable中，为了ref正确使用, 真正渲染调用afterDivideTableRender用数组。
                const { zlGridData, zlDivideData } = zlTransformData;
                await _this.gridRef.reloadTable(zlGridData, "zl", dsSourceData);
                const refs = await _this.gridRef.afterDivideTableRender(zlDivideData);
                setDirectionVal(value);
                setIsDirectionOpenModal(!isDirectionOpen);
                _this.gridRef.setTableContentChange(true, {
                    type: "修改纸张方向",
                    params: {
                        directionCfg: {
                            direction: value,
                        },
                    },
                });
                //更新整理模式下cpastable实例
                _this.gridRef && _this.gridRef?.dsTableRef?.setZlCpasTableRefs(refs);
            }
        }
        catch (e) {
            throw e;
        }
    };
    const directionPopoverContent = (_this) => {
        return (_jsx(Radio.Group, { options: directionOptions, onChange: onDirectionChange, value: directionVal }));
    };
    // const afterDivideTableRender = (gridDataArr) => {
    //   console.log("--------------渲染拆表数据---------------");
    //   const tableCount = gridDataArr.length;
    //   const dismantleTableElementArr = [];
    //   const dsName = _this.gridRef.props.name;
    //   for (let tableIndex = 0; tableIndex < tableCount; tableIndex++) {
    //     const gridData: any = gridDataArr[tableIndex];
    //     console.log(`gridData-${tableIndex + 1}`, gridData);
    //     // 动态创建n个 CpasTable 组件并设置属性
    //     const name = `${dsName}-more${tableIndex + 1}`;
    //     const elementProps: any = {
    //       type: "zl",
    //       name: name,
    //       tabLevel: 1,
    //       tabGroup: "tab-zl",
    //       mapRowsList: [],
    //       mapColumnsList: [],
    //       isShowMenuToolBar: false,
    //       gridData: gridData,
    //       isMultipleTableMode: true,
    //     };
    //     const tableHeight = _this.gridService.computerTableHeight(gridData);
    //     elementProps.height = tableHeight;
    //     const topBar = (
    //       <div className={"cpas-table-ds-bar-container"}>
    //         <div className={"cpas-table-ds-title"}>
    //           <span>货币资金2</span>
    //         </div>
    //         <div className={"cpas-table-ds-input"}>
    //           <AntInput placeholder={"在此输入附注中披露内容"} />
    //         </div>
    //       </div>
    //     );
    //     const bottomBar = (
    //       <div className={"cpas-table-ds-bar-container"}>
    //         <div className={"cpas-table-ds-input"}>
    //           <AntInput
    //             placeholder={"若单体附注中存在对上述披露内容的注释，请在此输入"}
    //           />
    //         </div>
    //         <div className={"cpas-table-ds-count"}>
    //           <span>平均数:40</span>
    //           <span>数量:40</span>
    //           <span>合计:40</span>
    //         </div>
    //       </div>
    //     );
    //     // 第一表只换数据，不从新渲染 目的是留着 isShowMenuToolBar={this.state.isShowZlMenuBar}
    //     if (tableIndex === 0) {
    //       elementProps.topBar = topBar;
    //       elementProps.isShowMenuToolBar = true;
    //       // delete _this.gridRef.dsTableRef.zlTableRef.bottomBar;
    //       // _this.gridRef.dsTableRef.zlTableRef.current.reloadTable(gridData);
    //       // continue;
    //     }
    //     if (tableIndex === tableCount - 1) {
    //       elementProps.bottomBar = bottomBar;
    //     }
    //     const element = React.createElement(CpasTable, elementProps, null);
    //     dismantleTableElementArr.push(element);
    //   }
    //   ReactDOM.render(
    //     dismantleTableElementArr,
    //     document.getElementById("cpasstableWapperRef2")
    //   );
    //   if (!dismantleTableMode) {
    //     cpassRef = _this.gridRef;
    //   }
    //   _this.gridRef?.dsTableRef?.setState({
    //     showDismantledTable: true,
    //   });
    //   let importDismantledTableJson = sessionStorage.importDismantledTableJson
    //     ? JSON.parse(sessionStorage.importDismantledTableJson)
    //     : undefined;
    //   if (!importDismantledTableJson) {
    //     message.info("拆表完成");
    //   }
    //   dismantleTableMode = true; // 设置成拆表模式
    //   sessionStorage.dismantleTableMode = JSON.stringify(dismantleTableMode);
    // };
    const handleResetTable = async () => {
        const refs = await _this.gridRef.handleResetTable();
        //设置整理模式下cpastable实例
        _this.gridRef && _this.gridRef?.dsTableRef?.setZlCpasTableRefs(refs);
        // 修改按钮的状态，让拆表按钮显示
        dismantleTableMode = false;
        // 隐藏拆表窗口
        setDismantleTableWindowOpen(false);
        //统计信息置空处理
        _this.gridRef.cpasTableRefs[0]?.hot.deselectCell();
        _this.gridRef.setTableContentChange(true, {
            type: "拆表恢复",
            params: {
                ..._this.gridRef.tableConfig,
            },
        });
    };
    // 拆表 Popover
    const DismantleTablePopoverContent = () => {
        const cpasData = _this.gridRef.dsSourceData;
        const cpasDataCopy = _.cloneDeep(cpasData);
        dismantleTableMode = _this.gridRef.tableConfig.dismantleTableMode;
        const handleDismantleTable = async () => {
            setDismantleTableWindowOpen(false);
            _this.headerService.getVisibleColumn();
            let ruleStr = dismantRule.current.input.value;
            const tableConfig = _this.gridRef.tableConfig; // "{}"
            if (!tableConfig) {
                _this.gridRef.tableConfig = {};
            }
            else if (typeof tableConfig === "string") {
                _this.gridRef.tableConfig = JSON.parse(_this.gridRef.tableConfig);
            }
            _this.gridRef.tableConfig.rule = ruleStr;
            _this.gridRef.tableConfig.dismantleTableMode = true;
            _this.gridRef.setTableContentChange(true, {
                type: "拆表",
                params: {
                    ..._this.gridRef.tableConfig,
                },
            });
            // 校验
            let rule = ruleStr.split(",");
            if (rule.length < 2) {
                message.info("至少输入两个参数");
                return;
            }
            // 必须都为数字
            for (let i = 0; i < rule.length; i++) {
                const ruleItem = rule[i];
                if (isNaN(ruleItem)) {
                    message.info("参数必须都要是数字");
                    return;
                }
            }
            for (let i = 1; i <= rule.length - 1; i++) {
                const ruleItem = rule[i]; // i=1 时 表示第一表的列取几个  i=1 值是2    i=2 为4   i=3为3
                if (ruleItem <= 0) {
                    message.info("每张表的列个数必须大于0");
                    return;
                }
            }
            const columnIndexThatEveryTableHas = rule[0]; // 2 表示前两列每张表都要有
            const headerColumn = _this.gridRef.headerService.headerColumn;
            if (columnIndexThatEveryTableHas < 0 ||
                columnIndexThatEveryTableHas >= headerColumn.length) {
                message.info("第一个参数（每张表都要有的列）必须大于等于0且小于表的列数");
                return;
            }
            const dsFormulaSourceData = _this.gridRef.props.dsTableRef.getFormulaSourceData();
            const tid = _this?.gridRef?.props?.notes?.tid;
            const result = await getDsToZlData(cpasDataCopy, _this.gridRef.tableConfig, dsFormulaSourceData, tid);
            if (result && result.data) {
                const resultData = result.data;
                const { zlGridData, zlDivideData } = resultData;
                await _this.gridRef.reloadTable(zlGridData, "zl", cpasDataCopy);
                const refs = await _this.gridRef.afterDivideTableRender(zlDivideData);
                //更新整理模式下cpastabl实例
                //更新整理模式下cpastable实例
                _this.gridRef && _this.gridRef?.dsTableRef?.setZlCpasTableRefs(refs);
            }
            dismantleTableMode = true;
            // sessionStorage.dismantleTableMode = JSON.stringify(true);
            // sessionStorage.rule = JSON.stringify(ruleStr);
            // if (gridDataArr.length > 0) {
            //   _this.gridRef.afterDivideTableRender(gridDataArr);
            // }
        };
        useEffect(() => {
            console.log("_this.gridRef.tableConfig", _this.gridRef.tableConfig);
            if (_this.gridRef.tableConfig.dismantleTableMode) {
                dismantleTableMode = _this.gridRef.tableConfig.dismantleTableMode;
                const rule = _this.gridRef.tableConfig.rule;
                // 回显拆表规则
                dismantRule.current.input.value = rule;
            }
            else {
                dismantleTableMode = false;
                dismantRule.current.input.value = "";
            }
        }, []);
        return (_jsxs("div", { className: "dismantle-container", children: [_jsx("p", { children: "\u8BF7\u8F93\u5165\u62C6\u8868\u89C4\u5219\uFF0C\u5F62\u5F0F\u5982\uFF1A2,3,3" }), _jsx("p", { children: _jsx(Input, { ref: dismantRule }, "dismantRuleInput") }), _jsx("p", { children: _jsxs("div", { className: "dismantle-confirm-container", children: [_jsx(Button, { className: "dismantle-confirm-btn", size: "small", type: "primary", onClick: handleDismantleTable, disabled: dismantleTableMode, children: "\u786E\u8BA4" }), _jsx(Button, { className: "dismantle-reset-btn", size: "small", type: "primary", onClick: () => handleResetTable(), disabled: !dismantleTableMode, children: "\u6062\u590D" })] }) })] }));
    };
    useEffect(() => {
        const { filterCfg = null } = _this.gridRef.tableConfig || {};
        console.log(filterCfg, "tableConfig reduciton editor------------");
        if (filterCfg && filterCfg.num) {
            setIsHiddenMergeRow(true);
        }
        else {
            setIsHiddenMergeRow(false);
        }
    }, [isFilterOpen, isMergeOpen]);
    const direction = _this?.gridRef?.tableConfig?.directionCfg?.direction;
    useEffect(() => {
        setDirectionVal(direction);
    }, [direction]);
    const afterVisibleChange = () => {
        console.log("afterVisibleChange");
        console.log("_this.gridRef.tableConfig", _this.gridRef.tableConfig);
        if (_this.gridRef.tableConfig.dismantleTableMode) {
            dismantleTableMode = _this.gridRef.tableConfig.dismantleTableMode;
            const rule = _this.gridRef.tableConfig.rule;
            // 回显拆表规则
            dismantRule.current.input.value = rule;
        }
        else {
            dismantleTableMode = false;
            dismantRule.current.input.value = "";
        }
    };
    const mergeType = getHbTypeByZcbfid();
    const isZLButton = mergeType === MergeType.UNKNOW || mergeType === MergeType.TEMPLATE; //整理模式部分按钮需要在合并系统隐藏（报告系统/合并系统非模版编辑模式）
    const isMergeHB = mergeType === MergeType.HB_HBYDT || mergeType === MergeType.DT_HBYDT;
    return (_jsxs("div", { className: "table-design-tools data-design-one-model", children: [_jsx("div", { className: "tools-item-width-auto", children: _jsx(DropDownButton, { text: "\u6821\u9A8C\u516C\u5F0F", icon: "iconfont icon-xiaoyan", className: "min-width-dx-button", onButtonClick: () => {
                        onShowModal();
                    }, opened: false }) }), _jsx("div", { className: "tools-item-width-auto", children: _jsx(DropDownButton, { text: "\u5F52\u5E76", disabled: isHiddenMergeRow, icon: "iconfont icon-guibing", className: "min-width-dx-button", onButtonClick: () => {
                        onShowMergeModal();
                    }, opened: false }) }), isMergeHB ? null : (_jsxs(_Fragment, { children: [_jsx("div", { className: "tools-item-width-auto", children: _jsxs(Popover, { placement: "right", content: DismantleTablePopoverContent, trigger: "click", open: dismantleTableWindowOpen, onOpenChange: handleOpenChange, 
                            // afterVisibleChange={afterVisibleChange}
                            destroyTooltipOnHide: true, children: [_jsx(CpasIcon, { type: "icon-chaibiao-lie", className: "cpas-icon" }), _jsx("span", { style: { marginLeft: 5 }, children: "\u62C6\u8868" })] }) }), _jsx("div", { className: "tools-item-width-auto", children: _jsxs(Popover, { placement: "bottom", content: () => yinCangPopoverContent(_this), trigger: "click", visible: hiddenPopoverVisible, onVisibleChange: handleHiddenPopoverVisibleChange, destroyTooltipOnHide: true, children: [_jsx(CpasIcon, { type: "icon-yanjing-yincang", className: "cpas-icon" }), _jsx("span", { style: { marginLeft: 5 }, children: "\u9690\u85CF" })] }) }), _jsx("div", { className: "tools-item-width-auto", children: _jsx(DropDownButton, { text: "\u7B5B\u9009", 
                            //disabled={true}
                            icon: "iconfont icon-filter", className: "min-width-dx-button", onButtonClick: () => {
                                onShowFilterModal();
                            }, opened: false }) }), _jsx("div", { className: "tools-item-width-auto", children: _jsx(DropDownButton, { text: "\u6392\u5E8F", 
                            //disabled={true}
                            icon: "iconfont icon-paixu", className: "min-width-dx-button", onButtonClick: () => {
                                onShowSortModal();
                            }, opened: false }) }), _jsx("div", { className: "tools-item-width-auto", children: _jsx(DropDownButton, { text: "\u5C3E\u5DEE", 
                            //disabled={true}
                            icon: "datafield", className: "min-width-dx-button", onButtonClick: () => {
                                onShowTailDifference();
                            }, opened: false }) }), _jsx("div", { className: "tools-item-width-auto", children: _jsxs(Popover, { placement: "bottom", content: () => directionPopoverContent(_this), trigger: "click", visible: isDirectionOpen, onVisibleChange: handleDirectionPopoverVisibleChange, destroyTooltipOnHide: true, children: [_jsx(CpasIcon, { type: "icon-zhizhangfangxiang", className: "cpas-icon" }), _jsx("span", { style: { marginLeft: 5 }, children: "\u7EB8\u5F20\u65B9\u5411" })] }) })] })), _jsx(CpasModalComponent, { isOpen: isOpen, handleOpen: onShowModal, params: _this }), _jsx(CpasMergeModal, { isOpen: isMergeOpen, handleOpen: onShowMergeModal, _this: _this }), _jsx(CpasFilter, { isOpen: isFilterOpen, handleOpen: onShowFilterModal, _this: _this }), _jsx(CpasSort, { isOpen: isSortOpen, handleOpen: onShowSortModal, _this: _this }), _jsx(CpasTailDiff, { isOpen: isTailDifference, handleOpen: onShowTailDifference, _this: _this })] }));
});
export default ReductionEditor;
